package lookas;

import java.io.File;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;

import lookas.foto.FotoPosition;
import lookas.track.Trip;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class JFotoGPS{
    private static final Log log = LogFactory.getLog(JFotoGPS.class);

    public static void main(String[] args) throws Exception{
        Options options = new Options();
        Option opt;

        opt = new Option("in", true, "iGo database file");
        opt.setRequired(true);
        opt.setArgs(1);
        options.addOption(opt);

        opt = new Option("out", true, "XML output file");
        opt.setRequired(true);
        opt.setArgs(1);
        options.addOption(opt);

        opt = new Option("dir", true, "Fotos directory");
        opt.setRequired(false);
        opt.setArgs(1);
        options.addOption(opt);

        opt = new Option("d", true, "Delta foto and time");
        opt.setRequired(false);
        opt.setArgs(2);
        options.addOption(opt);

        opt = new Option("p", true, "Fotos directory in output");
        opt.setRequired(false);
        opt.setArgs(1);
        options.addOption(opt);

        CommandLine cmd = null;
        try{
            CommandLineParser parser = new PosixParser();
            cmd = parser.parse(options, args);
        }catch(org.apache.commons.cli.ParseException e){
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("JFotoGPS", options, true);
            return;
        }

        Trip m = new Trip(cmd.getOptionValue("-in"));

        String[] delta = cmd.getOptionValues("-d");

        if(delta != null){
            Date date = null;
            String file = null;
            try{
                date = DateFormat.getDateTimeInstance().parse(delta[0]);
                file = delta[1];
            }catch(ParseException e){
                try{
                    date = DateFormat.getDateTimeInstance().parse(delta[1]);
                    file = delta[0];
                }catch(ParseException ex){}
            }

            if(date != null)
                m.setDelta(date.getTime()
                    - FotoPosition.readDate(new File(file)).getTime());
        }

        m.setDir(cmd.getOptionValue("-p"));
        String pathname = cmd.getOptionValue("-dir");
        if(pathname != null)
            m.setFotosDir(new File(pathname));

        m.saveXML(cmd.getOptionValue("-out"));
        log.info("OK");
    }
}
